import { ref, computed } from 'vue';
import type { HarFile, ComparisonResult } from '../types/har';
import { 
  saveHarFile, 
  getAllHarFiles, 
  deleteHarFile, 
  clearAllHarFiles,
  getStorageStats 
} from '../utils/storage';

// 状态
const harFiles = ref<HarFile[]>([]);
const selectedFile = ref<HarFile | null>(null);
const comparisonResult = ref<ComparisonResult | null>(null);
const isLoading = ref(false);
const error = ref<string>('');

// 对比文件选择状态
const baselineFileId = ref<string>('');
const targetFileId = ref<string>('');

// 计算属性
const fileCount = computed(() => harFiles.value.length);
const selectedFileId = computed(() => selectedFile.value?.id || '');
const hasFiles = computed(() => harFiles.value.length > 0);
const canCompare = computed(() => harFiles.value.length >= 2);

// 对比文件选择相关计算属性
const baselineFile = computed(() => harFiles.value.find(f => f.id === baselineFileId.value) || null);
const targetFile = computed(() => harFiles.value.find(f => f.id === targetFileId.value) || null);
const hasComparisonSelection = computed(() => baselineFileId.value !== '' && targetFileId.value !== '');
const canStartComparison = computed(() => baselineFileId.value !== '' && targetFileId.value !== '' && baselineFileId.value !== targetFileId.value);

// 获取文件统计信息
const fileStats = computed(() => {
  if (harFiles.value.length === 0) {
    return {
      totalSize: 0,
      averageSize: 0,
      oldestFile: null,
      newestFile: null
    };
  }
  
  const totalSize = harFiles.value.reduce((sum, file) => sum + file.size, 0);
  const averageSize = totalSize / harFiles.value.length;
  const uploadTimes = harFiles.value.map(file => file.uploadTime).sort();
  
  return {
    totalSize,
    averageSize,
    oldestFile: uploadTimes[0],
    newestFile: uploadTimes[uploadTimes.length - 1]
  };
});

// 按资源类型分组的文件统计
const filesByResourceType = computed(() => {
  const stats: Record<string, { count: number; totalSize: number }> = {};
  
  harFiles.value.forEach(file => {
    if (file.parsedData) {
      file.parsedData.forEach(entry => {
        const type = entry.resourceType;
        if (!stats[type]) {
          stats[type] = { count: 0, totalSize: 0 };
        }
        stats[type].count++;
        stats[type].totalSize += entry.size;
      });
    }
  });
  
  return stats;
});

// 操作函数
async function loadFiles() {
  isLoading.value = true;
  error.value = '';
  
  try {
    console.log('Loading files from IndexedDB...');
    harFiles.value = await getAllHarFiles();
    console.log('Loaded files from IndexedDB:', harFiles.value.length);
  } catch (err) {
    console.error('Failed to load files from IndexedDB:', err);
    error.value = err instanceof Error ? err.message : '加载文件失败';
  } finally {
    isLoading.value = false;
  }
}

async function addFile(harFile: HarFile) {
  isLoading.value = true;
  error.value = '';
  
  try {
    await saveHarFile(harFile);
    harFiles.value.push(harFile);
  } catch (err) {
    error.value = err instanceof Error ? err.message : '保存文件失败';
    throw err;
  } finally {
    isLoading.value = false;
  }
}

async function addFiles(files: HarFile[]) {
  isLoading.value = true;
  error.value = '';
  
  try {
    console.log('Adding files to IndexedDB:', files.map(f => f.name));
    for (const file of files) {
      await saveHarFile(file);
      console.log('Saved file to IndexedDB:', file.name);
    }
    harFiles.value.push(...files);
    console.log('Updated local state with', files.length, 'files');
  } catch (err) {
    console.error('Failed to save files to IndexedDB:', err);
    error.value = err instanceof Error ? err.message : '保存文件失败';
    throw err;
  } finally {
    isLoading.value = false;
  }
}

function selectFile(fileId: string) {
  const file = harFiles.value.find(f => f.id === fileId);
  selectedFile.value = file || null;
}

function selectFileByIndex(index: number) {
  if (index >= 0 && index < harFiles.value.length) {
    selectedFile.value = harFiles.value[index] || null;
  }
}

function clearSelection() {
  selectedFile.value = null;
}

async function removeFile(fileId: string) {
  isLoading.value = true;
  error.value = '';
  
  try {
    await deleteHarFile(fileId);
    harFiles.value = harFiles.value.filter(f => f.id !== fileId);
    
    // 如果删除的是当前选中的文件，清除选择
    if (selectedFile.value?.id === fileId) {
      selectedFile.value = null;
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '删除文件失败';
    throw err;
  } finally {
    isLoading.value = false;
  }
}

async function clearAllFiles() {
  isLoading.value = true;
  error.value = '';
  
  try {
    await clearAllHarFiles();
    harFiles.value = [];
    selectedFile.value = null;
    comparisonResult.value = null;
  } catch (err) {
    error.value = err instanceof Error ? err.message : '清空文件失败';
    throw err;
  } finally {
    isLoading.value = false;
  }
}

function setComparisonResult(result: ComparisonResult | null) {
  comparisonResult.value = result;
}

function clearComparison() {
  comparisonResult.value = null;
}

// 对比文件选择操作
function setBaselineFile(fileId: string) {
  baselineFileId.value = fileId;
}

function setTargetFile(fileId: string) {
  targetFileId.value = fileId;
}

function clearComparisonSelection() {
  baselineFileId.value = '';
  targetFileId.value = '';
}

function swapComparisonFiles() {
  const temp = baselineFileId.value;
  baselineFileId.value = targetFileId.value;
  targetFileId.value = temp;
}

// 文件搜索和过滤
function searchFiles(query: string): HarFile[] {
  if (!query.trim()) return harFiles.value;
  
  const lowerQuery = query.toLowerCase();
  return harFiles.value.filter(file => 
    file.name.toLowerCase().includes(lowerQuery)
  );
}

function filterFilesBySize(minSize: number, maxSize: number): HarFile[] {
  return harFiles.value.filter(file => 
    file.size >= minSize && file.size <= maxSize
  );
}

function filterFilesByDate(startDate: Date, endDate: Date): HarFile[] {
  return harFiles.value.filter(file => 
    file.uploadTime >= startDate && file.uploadTime <= endDate
  );
}

// 文件排序
function sortFilesBy(property: 'name' | 'size' | 'uploadTime', direction: 'asc' | 'desc' = 'asc') {
  harFiles.value.sort((a, b) => {
    let aValue: any = a[property];
    let bValue: any = b[property];
    
    if (property === 'uploadTime') {
      aValue = aValue.getTime();
      bValue = bValue.getTime();
    }
    
    if (direction === 'asc') {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
}

// 获取存储统计
async function getStorageStatistics() {
  try {
    return await getStorageStats();
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取存储统计失败';
    return null;
  }
}

// 重置状态
function reset() {
  harFiles.value = [];
  selectedFile.value = null;
  comparisonResult.value = null;
  isLoading.value = false;
  error.value = '';
  baselineFileId.value = '';
  targetFileId.value = '';
}

// 导出状态管理
export const useHarStore = () => {
  return {
    // 状态
    harFiles,
    selectedFile,
    comparisonResult,
    isLoading,
    error,
    baselineFileId,
    targetFileId,
    
    // 计算属性
    fileCount,
    selectedFileId,
    hasFiles,
    canCompare,
    fileStats,
    filesByResourceType,
    baselineFile,
    targetFile,
    hasComparisonSelection,
    canStartComparison,
    
    // 操作函数
    loadFiles,
    addFile,
    addFiles,
    selectFile,
    selectFileByIndex,
    clearSelection,
    removeFile,
    clearAllFiles,
    setComparisonResult,
    clearComparison,
    setBaselineFile,
    setTargetFile,
    clearComparisonSelection,
    swapComparisonFiles,
    searchFiles,
    filterFilesBySize,
    filterFilesByDate,
    sortFilesBy,
    getStorageStatistics,
    reset
  };
};

// 创建只读代理
function readonly<T>(target: T): T {
  return new Proxy(target as any, {
    get(target, key) {
      const value = target[key];
      if (value && typeof value === 'object') {
        return readonly(value);
      }
      return value;
    },
    set() {
      console.warn('状态是只读的，请使用相应的操作函数来修改状态');
      return false;
    }
  });
}
